package com.smh.hmdianping.util;

import cn.hutool.core.lang.UUID;
import com.smh.hmdianping.interfaces.ILock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author shiminghui
 * @date 2025/3/29 11:30
 * @description: TODO
 */
@Slf4j
public class SimpleRedisLock implements ILock {
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    private static final String LOCK_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<Long>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("/static/unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    private final StringRedisTemplate redisTemplate;
    private final String keyName;

    public SimpleRedisLock(StringRedisTemplate redisTemplate, String keyName) {
        this.redisTemplate = redisTemplate;
        this.keyName = keyName;
    }

    @Override
    public boolean tryLock(long timeoutSec, TimeUnit unit) {
        // 获取当前的线程的id
        String threadId = Thread.currentThread().getId() + "";
        Boolean b = redisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + keyName, ID_PREFIX + threadId, timeoutSec, unit);
        return Boolean.TRUE.equals(b);
    }

    @Override
    public void unLock() {
        redisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(LOCK_PREFIX + keyName),
                ID_PREFIX + Thread.currentThread().getId()
        );
    }

/*    @Override
    public void unLock() {
        // 获取锁的标识
        String lockId = redisTemplate.opsForValue().get(LOCK_PREFIX + keyName);
        // 获取当前线程的id
        String threadId = Thread.currentThread().getId() + "";

        if ((ID_PREFIX+threadId).equals(lockId)){ // 这里在极端情况下还是会误删别人的锁
            // 释放锁
            Boolean delete = redisTemplate.delete(LOCK_PREFIX + keyName);
            if (!Boolean.TRUE.equals(delete)) {
                log.debug("删除锁失败,线程id为:{}", threadId);
            }
        }
    }*/
}
